<?php

namespace yunj;

abstract class Enum {

    /**
     * Notes: 获取所有枚举项
     * Author: Uncle-L
     * Date: 2021/8/9
     * Time: 17:06
     * @return array
     */
    public static function options(): array {
        return [];
    }

    /**
     * Notes: 判断枚举项是否存在
     * Author: Uncle-L
     * Date: 2021/8/9
     * Time: 17:06
     * @param $code
     * @return bool
     */
    public static function isExist($code): bool {
        static $codeArr;
        $codeArr = $codeArr ?: array_keys(static::options());
        return in_array($code, $codeArr);
    }

    /**
     * Notes: 每个枚举元素的属性集合获取
     * Author: Uncle-L
     * Date: 2021/10/19
     * Time: 14:29
     * @param $code
     * @param array $default
     * @return array|mixed
     */
    public static function attr($code, array $default = []) {
        $options = static::options();
        return array_key_exists($code, $options) ? $options[$code] : $default;
    }

    /**
     * Notes: 每个枚举元素的指定属性集合获取
     * Author: Uncle-L
     * Date: 2021/8/9
     * Time: 17:06
     * @param string $attr
     * @param array $default
     * @return array
     */
    public static function attrOptions(string $attr = "title", array $default = []): array {
        static $options;
        $options = $options ?: [];
        if (!$options) {
            $_options = static::options();
            foreach ($_options as $k => $v)
                foreach ($v as $kk => $vv) $options[$kk][$k] = $vv;
        }
        return isset($options[$attr]) ? $options[$attr] : $default;
    }

    /**
     * Notes: 属性对应枚举项
     * Author: Uncle-L
     * Date: 2021/8/9
     * Time: 17:07
     * @param string $attr
     * @param $attrValue
     * @return false|int|string
     */
    public static function attrToCode(string $attr, $attrValue) {
        $options = static::attrOptions($attr);
        $code = array_search($attrValue, $options);
        return $code;
    }

    /**
     * Notes: 枚举项标题获取
     * Author: Uncle-L
     * Date: 2021/8/9
     * Time: 17:07
     * @param $code
     * @param string $default
     * @return string
     */
    public static function title($code, string $default = ''): string {
        $options = static::attrOptions("title");
        return isset($options[$code]) ? $options[$code] : $default;
    }

}